package com.ruoyi.system.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.config.RedissonLockComponent;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.ProductCategory;
import com.ruoyi.system.domain.ProductKey;
import com.ruoyi.system.mapper.ProductCategoryMapper;
import com.ruoyi.system.service.IProductKeySevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ProductMapper;
import com.ruoyi.system.domain.Product;
import com.ruoyi.system.service.IProductService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品Service业务层处理
 *
 * @author ruoyi
 * @date 2022-05-03
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {

    @Autowired
    private IProductKeySevice productKeySevice;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private IProductService productService;

    @Autowired
    private RedissonLockComponent redissonLockComponent;

    @Autowired
    private ProductCategoryMapper productCategoryMapper;

    /**
     * 查询商品
     *
     * @param id 商品主键
     * @return 商品
     */
    @Override
    public Product selectProductById(String id)
    {
        return productMapper.selectProductById(id);
    }

    /**
     * 查询商品列表
     *
     * @param product 商品
     * @return 商品
     */
    @Override
    public List<Product> selectProductList(Product product) {
        return productMapper.selectProductList(product);
    }

    @Override
    public Product selectProduct(Product product) {
        return productMapper.selectProduct(product);
    }

    /**
     * 新增商品
     *
     * @param product 商品
     * @return 结果
     */
    @Override
    public int insertProduct(Product product) {
        product.setCreateTime(DateUtils.getNowDate());

        if (Objects.isNull(product.getType())) {
            throw new ServiceException("请选择商品类型");
        }
        ProductCategory productCategory = productCategoryMapper.selectById(product.getCategoryId());
        Optional.ofNullable(productCategory).orElseThrow(() -> new ServiceException("无效分类"));
        this.save(product);
        return 1;

    }

    /**
     * 修改商品
     *
     * @param product 商品
     * @return 结果
     */
    @Override
    @Transactional
    public int updateProduct(Product product) {
        Product byId = this.getById(product.getId());
        Optional.ofNullable(byId).orElseThrow(() -> new ServiceException("无效商品"));
        if (Objects.isNull(product.getType())) {
            throw new ServiceException("请选择商品类型");
        }
        ProductCategory productCategory = productCategoryMapper.selectProductCategoryById(product.getCategoryId());
        Optional.ofNullable(productCategory).orElseThrow(() -> new ServiceException("无效分类"));
        this.updateById(product);
        return 1;
    }

    /**
     * 批量删除商品
     *
     * @param ids 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteProductByIds(String[] ids)
    {
        return productMapper.deleteProductByIds(ids);
    }
    @Override
    public int delete(Product product) {
        return productMapper.delete(product);
    }

    /**
     * 删除商品信息
     *
     * @param id 商品主键
     * @return 结果
     */
    @Override
    public int deleteProductById(String id)
    {
        return productMapper.deleteProductById(id);
    }

    @Override
    @Transactional
    public void reduceStock(Long id, Integer count, Long paymentRecordId) {
        Optional.ofNullable(count).orElseThrow(() -> new ServiceException("扣减数量未明确"));
        Optional.ofNullable(id).orElseThrow(() -> new ServiceException("商品不存在"));
        redissonLockComponent.execByDistributedLock("update_stock:" + id, 2L, () ->{
            Product product = productMapper.selectForUpdate(id);
            Optional.ofNullable(product).orElseThrow(() -> new ServiceException("商品不存在"));
            /*if (NumberUtil.compare(count, product.getStock()) > 0) {
                throw new ServiceException("商品数量不足");
            }*/
            // 随机选择足够数量的卡密进行记录
            List<ProductKey> productKeys = productKeySevice.getNoSellProductKeysAndLimitCount(product.getId());

            if (productKeys.size() < count) {
                throw new ServiceException("商品数量不足");
            }
            // 修改卡密信息状态为已卖出
            productKeys = productKeys.stream()
                    .limit(count)
                    .map(key -> {
                        ProductKey productKey = new ProductKey();
                        productKey.setId(key.getId());
                        productKey.setPaymentRecordId(paymentRecordId);
                        productKey.setIsSell("Y");
                        return productKey;
                    })
                    .collect(Collectors.toList());
            // 更新买家到卡密上
            productKeySevice.updateBatchById(productKeys);
            productService.updateStockNoLock(Arrays.asList(id));
            return true;
        });


    }

    @Override
    @Transactional
    public void updateStockNoLock(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return;
        }
        ids.forEach(id -> {
            List<ProductKey> productKeys = productKeySevice.queryNotSelledProductKey(id);
            this.update(
                    Wrappers.lambdaUpdate(Product.class)
                            .eq(Product::getId, id)
                            .set(Product::getStock, productKeys.size())
            );
        });
    }

}
